package com.dzl.enterprise.service.impl;

import com.dzl.admin.pojo.SysAdmin;
import com.dzl.admin.service.SysAdminService;
import com.dzl.base.query.BaseQuery;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.enterprise.dao.WelfareEnterpriseMapper;
import com.dzl.enterprise.pojo.WelfareEnterprise;
import com.dzl.enterprise.pojo.dto.WelfareEnterpriseSaveDto;
import com.dzl.enterprise.pojo.vo.WelfareEnterpriseVo;
import com.dzl.enterprise.service.WelfareEnterpriseService;
import com.dzl.util.AppUtils;
import com.dzl.util.EmptyUtils;
import com.dzl.util.ImageUtils;
import com.dzl.util.PasswordUtil;
import com.dzl.util.wx.constant.WxConstant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 企业管理(WelfareEnterprise)业务实现类
 * @author liuguanjun
 * @since 2021-09-06 14:29:41
 */
@Service("welfareEnterpriseService")
public class WelfareEnterpriseServiceImpl extends BaseServiceImpl<WelfareEnterprise> implements WelfareEnterpriseService {

    @Autowired
    private WelfareEnterpriseMapper mapper;
    @Autowired
    private SysAdminService sysAdminService;


    @Override
    public PageInfo<WelfareEnterpriseVo> selectWelfareEnterpriseListPage(BaseQuery query) {
        PageHelper.startPage(query);
        List<WelfareEnterpriseVo> list = mapper.selectWelfareEnterpriseList(query);
        if(EmptyUtils.isNotEmpty(list)) {
            list.forEach(welfareEnterprise -> {
                welfareEnterprise.setEnterpriseLogo(ImageUtils.setImageSrc(welfareEnterprise.getEnterpriseLogo()));
                welfareEnterprise.setBusinessLicense(ImageUtils.setImageSrc(welfareEnterprise.getBusinessLicense()));
            });
        }
        PageInfo<WelfareEnterpriseVo> page = new PageInfo<WelfareEnterpriseVo>(list);
        return page;
    }

    @Override
    public WelfareEnterprise selectWelfareEnterpriseByDomain(String domain) {
        WelfareEnterprise query = new WelfareEnterprise();
        query.setStatus(CommonConstants.YES);
        query.setDomain(domain+"");
        List<WelfareEnterprise> list = mapper.select(query);
        return EmptyUtils.isNotEmpty(list)?list.get(0):null;
    }

    @Override
    public WelfareEnterpriseVo selectWelfareEnterpriseById(Integer id) {
        WelfareEnterpriseVo welfareEnterpriseVo = new WelfareEnterpriseVo();
        WelfareEnterprise welfareEnterprise = mapper.selectByPrimaryKey(id);
        if(EmptyUtils.isNotEmpty(welfareEnterprise)){
            welfareEnterprise.setEnterpriseLogo(ImageUtils.setImageSrc(welfareEnterprise.getEnterpriseLogo()));
            welfareEnterprise.setBusinessLicense(ImageUtils.setImageSrc(welfareEnterprise.getBusinessLicense()));
            welfareEnterprise.setQrcode(ImageUtils.setImageSrc(welfareEnterprise.getQrcode()));
            BeanUtils.copyProperties(welfareEnterprise,welfareEnterpriseVo);
            SysAdmin sysAdminQuery = new SysAdmin();
            sysAdminQuery.setEnterpriseId(id);
            sysAdminQuery.setIsAdmin(CommonConstants.YES);
            sysAdminQuery.setStatus(CommonConstants.YES);
            sysAdminQuery.setType(CommonConstants.SYS_ADMIN_TYPE.TFB);
            SysAdmin sysAdmin = sysAdminService.selectOne(sysAdminQuery);
            if(EmptyUtils.isNotEmpty(sysAdmin)){
                welfareEnterpriseVo.setAccount(sysAdmin.getPhone());
                if(EmptyUtils.isNotEmpty(sysAdmin.getPassword())){
                    welfareEnterpriseVo.setPassword(PasswordUtil.AESDecrypt(sysAdmin.getPassword()));
                }
            }
            sysAdminQuery.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
            sysAdmin = sysAdminService.selectOne(sysAdminQuery);
            if(EmptyUtils.isNotEmpty(sysAdmin)){
                welfareEnterpriseVo.setPhone(sysAdmin.getPhone());
            }
        }
        return welfareEnterpriseVo;
    }

    @Override
    public Integer saveWelfareEnterprise(WelfareEnterpriseSaveDto welfareEnterprise) {
        if(EmptyUtils.isEmpty(welfareEnterprise.getId())) {
            //判断企业名称是否已存在
            WelfareEnterprise welfareEnterpriseQuery = new WelfareEnterprise();
            welfareEnterpriseQuery.setEnterpriseName(welfareEnterprise.getEnterpriseName());
            welfareEnterpriseQuery.setStatus(CommonConstants.YES);
            int count = mapper.selectCount(welfareEnterpriseQuery);
            if(count>0){
                throw new CommonException("企业名称已存在，请重新输入");
            }
            welfareEnterpriseQuery.setEnterpriseName(null);
            welfareEnterpriseQuery.setEnterpriseAbbreviation(welfareEnterprise.getEnterpriseAbbreviation());
            count = mapper.selectCount(welfareEnterpriseQuery);
            if(count>0){
                throw new CommonException("企业简称已存在，请重新输入");
            }
            welfareEnterprise.setStatus(CommonConstants.YES);
            welfareEnterprise.setCreateTime(new Date());
            welfareEnterprise.setIsApi(CommonConstants.NO);
            welfareEnterprise.setIsTfb(CommonConstants.NO);
            welfareEnterprise.setIsOpenapp(CommonConstants.NO);
            welfareEnterprise.setQrcode(null);
            welfareEnterprise.setDomain(null);
            welfareEnterprise.setAppRuleConfig(null);
            welfareEnterprise.setIsSelfSupport(CommonConstants.NO);
            return mapper.insertSelective(welfareEnterprise);
        }else{
            if(welfareEnterprise.getUpdateType()==0){
                //修改基本信息
                Example welfareEnterpriseExample = new Example(WelfareEnterprise.class);
                welfareEnterpriseExample.createCriteria().andEqualTo("enterpriseName", welfareEnterprise.getEnterpriseName()).andEqualTo("status",CommonConstants.YES)
                        .andNotEqualTo("id",welfareEnterprise.getId());
                int count = mapper.selectCountByExample(welfareEnterpriseExample);
                if(count>0){
                    throw new CommonException("企业名称已存在，请重新输入");
                }
                Example welfareEnterpriseAbbreviationExample = new Example(WelfareEnterprise.class);
                welfareEnterpriseAbbreviationExample.createCriteria().andEqualTo("enterpriseAbbreviation", welfareEnterprise.getEnterpriseAbbreviation()).andEqualTo("status",CommonConstants.YES)
                        .andNotEqualTo("id",welfareEnterprise.getId());
                count = mapper.selectCountByExample(welfareEnterpriseAbbreviationExample);
                if(count>0){
                    throw new CommonException("企业简称已存在，请重新输入");
                }
                welfareEnterprise.setDomain(null);
                welfareEnterprise.setQrcode(null);
                welfareEnterprise.setIsTfb(null);
                welfareEnterprise.setIsApi(null);
                welfareEnterprise.setAppRuleConfig(null);
                welfareEnterprise.setIsSelfSupport(null);
            }else if(welfareEnterprise.getUpdateType()==1){
                //修改兔福宝配置
                if (EmptyUtils.isNotEmpty(welfareEnterprise.getDomain())) {

                    Example welfareEnterpriseExample = new Example(WelfareEnterprise.class);
                    welfareEnterpriseExample.createCriteria().andEqualTo("domain", welfareEnterprise.getDomain()).andEqualTo("status",CommonConstants.YES)
                            .andNotEqualTo("id",welfareEnterprise.getId());
                    int count = mapper.selectCountByExample(welfareEnterpriseExample);
                    if(count>0){
                        throw new CommonException("后台链接已存在，请重新输入");
                    }
                }
                if(EmptyUtils.isNotEmpty(welfareEnterprise.getAccount())){
                    //查询该企业主账号
                    SysAdmin sysAdminQuery = new SysAdmin();
                    sysAdminQuery.setEnterpriseId(welfareEnterprise.getId());
                    sysAdminQuery.setIsAdmin(CommonConstants.YES);
                    sysAdminQuery.setStatus(CommonConstants.YES);
                    sysAdminQuery.setType(CommonConstants.SYS_ADMIN_TYPE.TFB);
                    List<SysAdmin> sysAdmins = sysAdminService.select(sysAdminQuery);
                    SysAdmin mainSysAdmin = EmptyUtils.isNotEmpty(sysAdmins)?sysAdmins.get(0):null;
                    if(EmptyUtils.isNotEmpty(mainSysAdmin)){
                        //如果当前账号与该企业主账号不一致，则修改主账号
                        if(!mainSysAdmin.getPhone().equals(welfareEnterprise.getAccount()) || !mainSysAdmin.getPassword().equals(PasswordUtil.AESEncrypt(welfareEnterprise.getPassword()))){
                            mainSysAdmin.setType(CommonConstants.SYS_ADMIN_TYPE.TFB);
                            mainSysAdmin.setUserName("超级管理员");
                            mainSysAdmin.setPhone(welfareEnterprise.getAccount());
                            mainSysAdmin.setPassword(welfareEnterprise.getPassword());
                            mainSysAdmin.setUpdateTime(new Date());
                            sysAdminService.saveAdmin(mainSysAdmin);
                        }
                        welfareEnterprise.setDomain(null);
                    }else{
                        //创建主账号
                        SysAdmin sysAdmin = new SysAdmin();
                        sysAdmin.setEnterpriseId(welfareEnterprise.getId());
                        sysAdmin.setUserName("超级管理员");
                        sysAdmin.setPhone(welfareEnterprise.getAccount());
                        if(EmptyUtils.isEmpty(welfareEnterprise.getPassword())){
                            sysAdmin.setPassword("123456");
                        }else{
                            sysAdmin.setPassword(welfareEnterprise.getPassword());
                        }
                        sysAdmin.setIsAdmin(CommonConstants.YES);
                        sysAdmin.setType(CommonConstants.SYS_ADMIN_TYPE.TFB);
                        sysAdminService.saveAdmin(sysAdmin);
                        //创建二维码
                        String appId = WxConstant.SAAS_APPID;
                        String appSecret = WxConstant.SAAS_APPSCERET;
                        String appletHomePath = "pages/home/index?enterpriseId="+welfareEnterprise.getId();
                        String qrcode = ImageUtils.getWxCode(appletHomePath,appId,appSecret);
                        welfareEnterprise.setQrcode(qrcode);
                    }
                }
            }else if(welfareEnterprise.getUpdateType()==2){
                //修改API配置

            }else if(welfareEnterprise.getUpdateType()==3){
                //修改独立部署配置
                if(EmptyUtils.isNotEmpty(welfareEnterprise.getPhone())){
                    //查询该企业主账号
                    SysAdmin sysAdminQuery = new SysAdmin();
                    sysAdminQuery.setEnterpriseId(welfareEnterprise.getId());
                    sysAdminQuery.setIsAdmin(CommonConstants.YES);
                    sysAdminQuery.setStatus(CommonConstants.YES);
                    sysAdminQuery.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
                    List<SysAdmin> sysAdmins = sysAdminService.select(sysAdminQuery);
                    SysAdmin mainSysAdmin = EmptyUtils.isNotEmpty(sysAdmins)?sysAdmins.get(0):null;
                    if(EmptyUtils.isNotEmpty(mainSysAdmin)){
                        //如果当前账号与该企业主账号不一致，则修改主账号
                        if(!mainSysAdmin.getPhone().equals(welfareEnterprise.getPhone())){
                            mainSysAdmin.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
                            mainSysAdmin.setUserName("超级管理员");
                            mainSysAdmin.setPhone(welfareEnterprise.getPhone());
                            mainSysAdmin.setPassword(null);
                            mainSysAdmin.setUpdateTime(new Date());
                            sysAdminService.saveAdmin(mainSysAdmin);
                        }
                    }else{
                        //创建主账号
                        SysAdmin sysAdmin = new SysAdmin();
                        sysAdmin.setEnterpriseId(welfareEnterprise.getId());
                        sysAdmin.setUserName("超级管理员");
                        sysAdmin.setPhone(welfareEnterprise.getPhone());
                        sysAdmin.setIsAdmin(CommonConstants.YES);
                        sysAdmin.setType(CommonConstants.SYS_ADMIN_TYPE.APP);
                        sysAdmin.setRoleId(1);
                        sysAdminService.saveAdmin(sysAdmin);
                    }
                }
            }
            welfareEnterprise.setUpdateTime(new Date());
            return mapper.updateByPrimaryKeySelective(welfareEnterprise);
        }
    }

    @Override
    public Map openWelfareEnterpriseApi(Integer enterpriseId) {
        WelfareEnterprise welfareEnterprise = new WelfareEnterprise();
        welfareEnterprise.setId(enterpriseId);
        welfareEnterprise.setIsApi(CommonConstants.YES);
        welfareEnterprise.setUpdateTime(new Date());
        welfareEnterprise.setApiId(AppUtils.getAppId());
        welfareEnterprise.setApiSecret(AppUtils.getAppSecret(welfareEnterprise.getAppid()));
        mapper.updateByPrimaryKeySelective(welfareEnterprise);
        Map map = Maps.newHashMapWithExpectedSize(2);
        map.put("apiid",welfareEnterprise.getAppid());
        map.put("apisecret",welfareEnterprise.getAppsecret());
        return map;
    }

    @Override
    public Integer saveEnterpriseIntegral(Integer id, BigDecimal amount) {
        WelfareEnterprise welfareEnterprise = mapper.selectByPrimaryKey(id);
        //最大金额为9999999999.99
        if (welfareEnterprise.getTotalIntegral().add(amount).compareTo(new BigDecimal("9999999999.99")) <= 0  && welfareEnterprise.getBalanceIntegral().add(amount).compareTo(new BigDecimal("9999999999.99")) <= 0){
            welfareEnterprise.setTotalIntegral(welfareEnterprise.getTotalIntegral().add(amount));
            welfareEnterprise.setBalanceIntegral(welfareEnterprise.getBalanceIntegral().add(amount));
            mapper.updateByPrimaryKeySelective(welfareEnterprise);
            return 1;
        }
        return 0;
    }


}
